<?php

function runQuery($query) {
    global $config;
    if (strlen($query) > 0) {
        $resource = mysql_query($query, $config['mysql']['link']) or die("Query: ".$query.", Error: ".mysql_error());
        return $resource;
    }
	else {
        return null;
    }
}

function authenticateUser($name, $pass){
    global $config;
    $hashpass = hash("sha256", $pass);
    
    $query='
        Select  username
        From    `'.$config['mysql']['database'].'`.`Users`
        Where   username = "'.$name.'"
        And     password = "'.$hashpass.'"
    ';
    
    /* User Authenticated */
    if(mysql_num_rows(runQuery($query)) == 1)
        return true;
    
    return false;
}

function getVersion($type){
    global $config;
    $query = '
        Select	value
        From	ms2_settings
        Where	name = "'.$type.'"
    ';

    $record = mysql_fetch_assoc(runQuery($query));
    return $record['value'];
}

function generateSessionId(){
    global $config;
    // generate rand num
    srand(time());
    $randNum = rand(1000000000, 2147483647).rand(1000000000, 2147483647).rand(0,9);
    
    /* Check to see if it is un use */
    $query = '
        Select  session
        From    `'.$config['mysql']['database'].'`.`Users`
        Where   session = '.$randNum.'
    ';
    
    $resource = runQuery($query);
    if(mysql_num_rows($resource) == 0){
        return $randNum;
    } else {
        return generateSessionId();
    }
}

function userExists($username){
    global $config;
    
    $query = '
        Select  username
        From    `'.$config['mysql']['database'].'`.`Users`
        Where   username = "'.$username.'"
    ';
    
    $resource = runQuery($query);
    
    if(mysql_num_rows($resource) == 1){
        return true;
    } else {
        return false;
    }
}

function createNewUser($user, $password){
    global $config;
    $query = '
        Insert Into `'.$config['mysql']['database'].'`.`Users`
        (username, password)
        Values
        ("'.$user.'", "'.hash("sha256", $password).'")
    ';
    
    runQuery($query);
    
    if(mysql_affected_rows($config['mysql']['link']) == 1){
        return true;
    } else {
        return false;
    }
}

function checkMinecraftForUser($user, $password){
    $minecraftUrl = "http://www.minecraft.net/game/getversion.jsp";
    $postParams = "user=".$user."&password=".$password."&version=13";
    $response = do_post_request($minecraftUrl, $postParams);
    
    $premiumRegex = "/\b[0-9]{13}\b:\b\w+\b:$user:[-]?\b[0-9]+\b:/";
    $notPremiumRegex = "/User not premium/";
    
    if(preg_match($premiumRegex, $response) == 1){
        return true;
    } else if(preg_match($notPremiumRegex, $response) == 1){
        return true;
    } else {
        return false;
    }
}

function do_post_request($url, $data)
{
  $params = array('http' => array(
              'method' => 'POST',
              'content' => $data
            ));

  $ctx = stream_context_create($params);
  $fp = @fopen($url, 'rb', false, $ctx);
  if (!$fp) {
    throw new Exception("Problem with $url, $php_errormsg");
  }
  $response = @stream_get_contents($fp);
  if ($response === false) {
    throw new Exception("Problem reading data from $url, $php_errormsg");
  }
  return $response;
}

function loginUserById($id){
    global $sessLoggedIn;
    global $config;
    /* Get User Id */
    $query = '
	Select 	username
	From    `'.$config['mysql']['database'].'`.`Users`
	Where	id = "'.$id.'";
    ';
    
    $record = mysql_fetch_assoc(runQuery($query));
    
    /* set session id */
    $_SESSION['sessId'] = session_id();
    
    /* set time */
    $_SESSION['time'] = time();
    
    /* set username */
    $record = mysql_fetch_assoc(runQuery($query));
    $_SESSION['username'] = $record['username'];
    
    /* set userid */
    $_SESSION['userId'] = $id;
    
    /* Logged In! */
    $sessLoggedIn = true;
}

function loginUserByName($username){
    global $sessLoggedIn;
    global $config;
    global $sessFirstTime;
    
    /* Get User Id */
    $query = '
	Select 	id
	From    `'.$config['mysql']['database'].'`.`Users`
	Where	username = "'.$username.'";
    ';
    
    $record = mysql_fetch_assoc(runQuery($query));
    
    /* set session id */
    $_SESSION['sessId'] = session_id();
    
    /* set time */
    $_SESSION['time'] = time();
    
    /* set username */
    $_SESSION['username'] = $username;
    
    /* set userid */
    $record = mysql_fetch_assoc(runQuery($query));
    $_SESSION['userId'] = $record['id'];
    
    /* Sert First Login */
    $sessFirstTime = true;

    /* Logged In! */
    $sessLoggedIn = true;
}
?>